//package org.learn;
//
//import java.security.AccessControlContext;
//import java.security.AccessController;
//import java.util.HashSet;
//import java.util.List;
//import java.util.concurrent.BlockingQueue;
//import java.util.concurrent.RejectedExecutionException;
//import java.util.concurrent.RejectedExecutionHandler;
//import java.util.concurrent.ThreadFactory;
//import java.util.concurrent.ThreadPoolExecutor;
//import java.util.concurrent.TimeUnit;
//import java.util.concurrent.atomic.AtomicInteger;
//import java.util.concurrent.locks.Condition;
//import java.util.concurrent.locks.ReentrantLock;
//
///**
// * @Auther: qingle
// * @Date: 2024/9/9-0:31
// * @Description:
// * @version: 1.0
// */
//public class executeStudy {
//
//	private final AtomicInteger ctl = new AtomicInteger(ctlOf(RUNNING, 0));
//	private static final int COUNT_BITS = Integer.SIZE - 3;
//	private static final int CAPACITY   = (1 << COUNT_BITS) - 1;
//
//	// runState is stored in the high-order bits
//	private static final int RUNNING    = -1 << COUNT_BITS;
//	private static final int SHUTDOWN   =  0 << COUNT_BITS;
//	private static final int STOP       =  1 << COUNT_BITS;
//	private static final int TIDYING    =  2 << COUNT_BITS;
//	private static final int TERMINATED =  3 << COUNT_BITS;
//
//	// Packing and unpacking ctl
//	private static int runStateOf(int c)     { return c & ~CAPACITY; }
//	private static int workerCountOf(int c)  { return c & CAPACITY; }
//	private static int ctlOf(int rs, int wc) { return rs | wc; }
//
//	/*
//	 * Bit field accessors that don't require unpacking ctl.
//	 * These depend on the bit layout and on workerCount being never negative.
//	 */
//
//	private static boolean runStateLessThan(int c, int s) {
//		return c < s;
//	}
//
//	private static boolean runStateAtLeast(int c, int s) {
//		return c >= s;
//	}
//
//	private static boolean isRunning(int c) {
//		return c < SHUTDOWN;
//	}
//
//	/**
//	 * Attempts to CAS-increment the workerCount field of ctl.
//	 */
//	private boolean compareAndIncrementWorkerCount(int expect) {
//		return ctl.compareAndSet(expect, expect + 1);
//	}
//
//	/**
//	 * Attempts to CAS-decrement the workerCount field of ctl.
//	 */
//	private boolean compareAndDecrementWorkerCount(int expect) {
//		return ctl.compareAndSet(expect, expect - 1);
//	}
//
//	/**
//	 * Decrements the workerCount field of ctl. This is called only on
//	 * abrupt termination of a thread (see processWorkerExit). Other
//	 * decrements are performed within getTask.
//	 */
//	private void decrementWorkerCount() {
//		do {} while (! compareAndDecrementWorkerCount(ctl.get()));
//	}
//
//	/**
//	 * The queue used for holding tasks and handing off to worker
//	 * threads.  We do not require that workQueue.poll() returning
//	 * null necessarily means that workQueue.isEmpty(), so rely
//	 * solely on isEmpty to see if the queue is empty (which we must
//	 * do for example when deciding whether to transition from
//	 * SHUTDOWN to TIDYING).  This accommodates special-purpose
//	 * queues such as DelayQueues for which poll() is allowed to
//	 * return null even if it may later return non-null when delays
//	 * expire.
//	 */
//	private final BlockingQueue<Runnable> workQueue;
//
//	/**
//	 * Lock held on access to workers set and related bookkeeping.
//	 * While we could use a concurrent set of some sort, it turns out
//	 * to be generally preferable to use a lock. Among the reasons is
//	 * that this serializes interruptIdleWorkers, which avoids
//	 * unnecessary interrupt storms, especially during shutdown.
//	 * Otherwise exiting threads would concurrently interrupt those
//	 * that have not yet interrupted. It also simplifies some of the
//	 * associated statistics bookkeeping of largestPoolSize etc. We
//	 * also hold mainLock on shutdown and shutdownNow, for the sake of
//	 * ensuring workers set is stable while separately checking
//	 * permission to interrupt and actually interrupting.
//	 */
//	private final ReentrantLock mainLock = new ReentrantLock();
//
//	/**
//	 * Set containing all worker threads in pool. Accessed only when
//	 * holding mainLock.
//	 */
//	private final HashSet<ThreadPoolExecutor.Worker> workers = new HashSet<ThreadPoolExecutor.Worker>();
//
//	/**
//	 * Wait condition to support awaitTermination
//	 */
//	private final Condition termination = mainLock.newCondition();
//
//	/**
//	 * Tracks largest attained pool size. Accessed only under
//	 * mainLock.
//	 */
//	private int largestPoolSize;
//
//	/**
//	 * Counter for completed tasks. Updated only on termination of
//	 * worker threads. Accessed only under mainLock.
//	 */
//	private long completedTaskCount;
//
//	/*
//	 * All user control parameters are declared as volatiles so that
//	 * ongoing actions are based on freshest values, but without need
//	 * for locking, since no internal invariants depend on them
//	 * changing synchronously with respect to other actions.
//	 */
//
//	/**
//	 * Factory for new threads. All threads are created using this
//	 * factory (via method addWorker).  All callers must be prepared
//	 * for addWorker to fail, which may reflect a system or user's
//	 * policy limiting the number of threads.  Even though it is not
//	 * treated as an error, failure to create threads may result in
//	 * new tasks being rejected or existing ones remaining stuck in
//	 * the queue.
//	 *
//	 * We go further and preserve pool invariants even in the face of
//	 * errors such as OutOfMemoryError, that might be thrown while
//	 * trying to create threads.  Such errors are rather common due to
//	 * the need to allocate a native stack in Thread.start, and users
//	 * will want to perform clean pool shutdown to clean up.  There
//	 * will likely be enough memory available for the cleanup code to
//	 * complete without encountering yet another OutOfMemoryError.
//	 */
//	private volatile ThreadFactory threadFactory;
//
//	/**
//	 * Handler called when saturated or shutdown in execute.
//	 */
//	private volatile RejectedExecutionHandler handler;
//
//	/**
//	 * Timeout in nanoseconds for idle threads waiting for work.
//	 * Threads use this timeout when there are more than corePoolSize
//	 * present or if allowCoreThreadTimeOut. Otherwise they wait
//	 * forever for new work.
//	 */
//	private volatile long keepAliveTime;
//
//	/**
//	 * If false (default), core threads stay alive even when idle.
//	 * If true, core threads use keepAliveTime to time out waiting
//	 * for work.
//	 */
//	private volatile boolean allowCoreThreadTimeOut;
//
//	/**
//	 * Core pool size is the minimum number of workers to keep alive
//	 * (and not allow to time out etc) unless allowCoreThreadTimeOut
//	 * is set, in which case the minimum is zero.
//	 */
//	private volatile int corePoolSize;
//
//	/**
//	 * Maximum pool size. Note that the actual maximum is internally
//	 * bounded by CAPACITY.
//	 */
//	private volatile int maximumPoolSize;
//
//	/**
//	 * The default rejected execution handler
//	 */
//	private static final RejectedExecutionHandler defaultHandler =
//		new ThreadPoolExecutor.AbortPolicy();
//
//	/**
//	 * Permission required for callers of shutdown and shutdownNow.
//	 * We additionally require (see checkShutdownAccess) that callers
//	 * have permission to actually interrupt threads in the worker set
//	 * (as governed by Thread.interrupt, which relies on
//	 * ThreadGroup.checkAccess, which in turn relies on
//	 * SecurityManager.checkAccess). Shutdowns are attempted only if
//	 * these checks pass.
//	 *
//	 * All actual invocations of Thread.interrupt (see
//	 * interruptIdleWorkers and interruptWorkers) ignore
//	 * SecurityExceptions, meaning that the attempted interrupts
//	 * silently fail. In the case of shutdown, they should not fail
//	 * unless the SecurityManager has inconsistent policies, sometimes
//	 * allowing access to a thread and sometimes not. In such cases,
//	 * failure to actually interrupt threads may disable or delay full
//	 * termination. Other uses of interruptIdleWorkers are advisory,
//	 * and failure to actually interrupt will merely delay response to
//	 * configuration changes so is not handled exceptionally.
//	 */
//	private static final RuntimePermission shutdownPerm =
//		new RuntimePermission("modifyThread");
//
//	/* The context to be used when executing the finalizer, or null. */
//	private final AccessControlContext acc;
//
//
//	public ThreadPoolExecutor(int corePoolSize,
//	                          int maximumPoolSize,
//	                          long keepAliveTime,
//	                          TimeUnit unit,
//	                          BlockingQueue<Runnable> workQueue,
//	                          ThreadFactory threadFactory,
//	                          RejectedExecutionHandler handler) {
//		if (corePoolSize < 0 ||
//			maximumPoolSize <= 0 ||
//			maximumPoolSize < corePoolSize ||
//			keepAliveTime < 0)
//			throw new IllegalArgumentException();
//		if (workQueue == null || threadFactory == null || handler == null)
//			throw new NullPointerException();
//		this.acc = System.getSecurityManager() == null ?
//			null :
//			AccessController.getContext();
//		this.corePoolSize = corePoolSize;
//		this.maximumPoolSize = maximumPoolSize;
//		this.workQueue = workQueue;
//		this.keepAliveTime = unit.toNanos(keepAliveTime);
//		this.threadFactory = threadFactory;
//		this.handler = handler;
//	}
//
//	/**
//	 * Executes the given task sometime in the future.  The task
//	 * may execute in a new thread or in an existing pooled thread.
//	 *
//	 * If the task cannot be submitted for execution, either because this
//	 * executor has been shutdown or because its capacity has been reached,
//	 * the task is handled by the current {@code RejectedExecutionHandler}.
//	 *
//	 * @param command the task to execute
//	 * @throws RejectedExecutionException at discretion of
//	 *         {@code RejectedExecutionHandler}, if the task
//	 *         cannot be accepted for execution
//	 * @throws NullPointerException if {@code command} is null
//	 */
///**
// * 执行给定的任务，并根据需要管理线程。
// *
// * @param command 要执行的任务，不能为null
// * @throws NullPointerException 如果command为null时抛出此异常
// */
//
//	public void execute(Runnable command) {
//		if (command == null)
//			throw new NullPointerException();
//
		/**
		 * 按照以下三个步骤进行操作：
		 *
		 * 1. 如果当前运行的线程少于核心线程数，则尝试启动一个新线程来执行给定的任务。
		 *    addWorker 方法会原子地检查 runState 和 workerCount，防止在不应该增加线程时发出错误警报，
		 *    通过返回 false 来避免这种情况。
		 *
		 * 2. 如果任务能够成功入队，那么仍然需要再次检查是否应该添加线程（因为自上次检查以来已有线程死亡）
		 *    或者池子自进入此方法后已关闭。因此重新检查状态，如果已停止则回退入队操作，否则如果没有线程则启动新线程。
		 *
		 * 3. 如果无法将任务入队，则尝试添加新线程。如果失败，我们知道池子已关闭或饱和，因此拒绝任务。
		 */
//		int c = ctl.get();
//		if (workerCountOf(c) < corePoolSize) {
//			if (addWorker(command, true))
//				return;
//			c = ctl.get();
//		}
//		if (isRunning(c) && workQueue.offer(command)) {
//			int recheck = ctl.get();
//			if (! isRunning(recheck) && remove(command))
//				reject(command);
//			else if (workerCountOf(recheck) == 0)
//				addWorker(null, false);
//		}
//		else if (!addWorker(command, false))
//			reject(command);
//	}

	/**
	 * 开始一个有序的关闭过程，在此过程中会执行之前提交的任务，但不会接受任何新任务。
	 * 如果已经关闭，再次调用此方法不会产生额外的效果。
	 *
	 * <p>此方法不会等待之前提交的任务完成执行。如果需要等待任务完成，请使用
	 * {@link #awaitTermination}方法。
	 *
	 * @throws SecurityException 如果当前安全管理器不允许操作，则抛出此异常。
	 */
//	public void shutdown() {
//	    // 获取主锁，用于保护状态变更
//	    final ReentrantLock mainLock = this.mainLock;
//	    mainLock.lock();
//	    try {
//	        // 检查关闭访问权限
//	        checkShutdownAccess();
//	        // 将运行状态推进到SHUTDOWN状态
//	        advanceRunState(SHUTDOWN);
//	        // 中断所有空闲的工作者线程
//	        interruptIdleWorkers();
//	        // 为ScheduledThreadPoolExecutor提供的钩子，在关闭时可以执行额外的操作
//	        onShutdown();
//	    } finally {
//	        // 释放主锁
//	        mainLock.unlock();
//	    }
//	    // 尝试终止线程池，开始关闭流程
//	    tryTerminate();
//	}
//
//	/**
//	 * Attempts to stop all actively executing tasks, halts the
//	 * processing of waiting tasks, and returns a list of the tasks
//	 * that were awaiting execution. These tasks are drained (removed)
//	 * from the task queue upon return from this method.
//	 *
//	 * <p>This method does not wait for actively executing tasks to
//	 * terminate.  Use {@link #awaitTermination awaitTermination} to
//	 * do that.
//	 *
//	 * <p>There are no guarantees beyond best-effort attempts to stop
//	 * processing actively executing tasks.  This implementation
//	 * cancels tasks via {@link Thread#interrupt}, so any task that
//	 * fails to respond to interrupts may never terminate.
//	 *
//	 * @throws SecurityException {@inheritDoc}
//	 */
//	public List<Runnable> shutdownNow() {
//		List<Runnable> tasks;
//		final ReentrantLock mainLock = this.mainLock;
//		mainLock.lock();
//		try {
//			checkShutdownAccess();
//			advanceRunState(STOP);
//			interruptWorkers();
//			tasks = drainQueue();
//		} finally {
//			mainLock.unlock();
//		}
//		tryTerminate();
//		return tasks;
//	}
//
//	public boolean isShutdown() {
//		return ! isRunning(ctl.get());
//	}
//
//	/**
//	 * Returns true if this executor is in the process of terminating
//	 * after {@link #shutdown} or {@link #shutdownNow} but has not
//	 * completely terminated.  This method may be useful for
//	 * debugging. A return of {@code true} reported a sufficient
//	 * period after shutdown may indicate that submitted tasks have
//	 * ignored or suppressed interruption, causing this executor not
//	 * to properly terminate.
//	 *
//	 * @return {@code true} if terminating but not yet terminated
//	 */
//	public boolean isTerminating() {
//		int c = ctl.get();
//		return ! isRunning(c) && runStateLessThan(c, TERMINATED);
//	}
//}
